package com.ht.callback.function.impl;

import org.springframework.stereotype.Component;

import com.ht.callback.function.Function;
import com.ht.callback.wexinaes.AesException;
import com.ht.callback.wexinaes.WXBizMsgCrypt;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 平台函数：企业微信
 * @author asq
 * @createTime 2024年12月19日 08:26:30
 */
@Component
@Slf4j
public class QywxFunction implements Function {

	@Override
	public String active(JSONObject appConfig, JSONObject paramUrl, String body) {
		try {
			String token = getValue(appConfig, "Token");
			String encodingAesKey = getValue(appConfig, "EncodingAESKey");
			String receiveid = getValue(appConfig, "CorpId");
			
			WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(token, encodingAesKey, receiveid);
			return wxcpt.decrypt(paramUrl.getStr("echostr"));
		} catch (AesException e) {
			log.error("配置企业微信回调路径时出现异常:{}", e.getMessage(), e);
			return "error";
		}
	}

	@Override
	public String verifySign(JSONObject appConfig, JSONObject paramUrl, String body) {
		String token = getValue(appConfig, "Token");
		String encodingAesKey = getValue(appConfig, "EncodingAESKey");
		String receiveid = getValue(appConfig, "CorpId");
		
		// 获取url参数
		String signature = paramUrl.getStr("msg_signature");
		String timestamp = paramUrl.getStr("timestamp");
		String nonce = paramUrl.getStr("nonce");
		
		String desContent = null;
		try {
			WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(token, encodingAesKey, receiveid);
			desContent = wxcpt.DecryptMsg(signature, timestamp, nonce, body);
		} catch (AesException e) {
			log.error("处理企业微信回调时出现异常:{}", e.getMessage(), e);
		}
		
		return desContent;
	}

	@Override
	public String result(JSONObject paramUrl, String body) {
		JSONObject resultData = JSONUtil.createObj();
		resultData.set("errcode", 0);
		resultData.set("errmsg", "ok");
		return JSONUtil.toJsonStr(resultData);
	}
	
	private String getValue(JSONObject json, String name) {
	    if (json == null || StrUtil.isBlank(name)) {
	        return null;
	    }
	    
	    // 遍历 token_param
	    JSONArray tokenParams = json.getJSONArray("token_param");
	    if (tokenParams != null) {
	        for (int i = 0; i < tokenParams.size(); i++) {
	            JSONObject param = tokenParams.getJSONObject(i);
	            if (name.equals(param.getStr("name"))) {
	                return param.getStr("value");
	            }
	        }
	    }
	    
	    // 遍历 callback_decrypt
	    JSONArray callbackDecrypt = json.getJSONArray("callback_decrypt");
	    if (callbackDecrypt != null) {
	        for (int i = 0; i < callbackDecrypt.size(); i++) {
	            JSONObject param = callbackDecrypt.getJSONObject(i);
	            if (name.equals(param.getStr("name"))) {
	                return param.getStr("value");
	            }
	        }
	    }
	    
	    return null;
	}
}
